from fastapi import APIRouter, HTTPException
from app.models.student import Student
from pydantic import BaseModel

users = APIRouter()


@users.get("/users")
async def get_users():
    """
    获取所有用户
    :return:
    """
    users = await Student.all()
    return users

# 定义登录请求模型
class LoginRequest(BaseModel):
    username: str
    password: str
    role: str  # 添加角色字段


# 登录
# 登录接口
@users.post("/login")
async def login(login_data: LoginRequest):
    print(login_data)
    """
    登录
    :param login_data: 包含username, password和role的登录数据
    :return: 登录结果
    """
    # 根据角色查询不同表（示例，根据你的实际数据库结构调整）
    if login_data.role == "student":
        user = await Student.filter(username=login_data.username, password=login_data.password).first()
    elif login_data.role == "teacher":
        user = await Student.filter(username=login_data.username, password=login_data.password).first()
    elif login_data.role == "admin":
        user = await Student.filter(username=login_data.username, password=login_data.password).first()
    else:
        raise HTTPException(status_code=400, detail="无效的角色")

    if user:
        # 这里应该生成token，示例中简化处理
        return {
            "code": 200,
            "message": "登录成功",
            "data": {
                "token": "generated_token_here",  # 应该使用JWT等生成真实token
                "user_info": {
                    "username": user.username,
                    "role": login_data.role
                }
            }
        }
    else:
        raise HTTPException(status_code=401, detail="用户名或密码错误")
